package handlers

//上报任务情况
import (
	"cron-go/configs/error_code"
	"cron-go/internal/pkg/crontab/dao"
	"cron-go/internal/pkg/crontab/enum"
	"cron-go/internal/pkg/crontab/models"

	"github.com/go-liam/util/conv"
	"github.com/go-liam/util/response"
	"github.com/go-playground/validator/v10"
)

type UpdateTaskStatus struct {
	Req  *UpdateTaskStatusReq
	IDs  []int64
	List []*models.TaskMysqlModel
}

type UpdateTaskStatusReq struct {
	IDs      []string    `json:"ids" validate:"required" ` // 任务ID
	DoStatus int         `json:"doStatus" `                // 执行状态 0 默认 ,1 新跑任务 , 2 执行中 ,3 失败,10执行成功
	Info     interface{} `json:"info" `                    // 执行说明
}

func (s *UpdateTaskStatus) GetData() *response.APIResponse {
	if !s.CheckData() {
		return &response.APIResponse{Code: error_code.RequestParameter, Message: error_code.MsRequest, Data: ""}
	}
	s.Change()
	num := 0
	s.GetList()
	// update task doStatus
	dao.TaskDaoServer.UpdateDoStatus(s.IDs, s.Req.DoStatus)
	//log
	num = s.AddLog()
	// update finnish
	s.Finish()
	s.NewReady()
	return &response.APIResponse{Code: error_code.Success, Message: error_code.MsSuccess, Data: num}
}

func (s *UpdateTaskStatus) Change() {
	if s.Req == nil {
		return
	}
	s.IDs = conv.ArrayStringToInt64(s.Req.IDs)
}

func (s *UpdateTaskStatus) CheckData() bool {
	validate := validator.New()
	err := validate.Struct(s.Req)
	return err == nil
}

func (s *UpdateTaskStatus) AddLog() int {
	num := 0
	for _, id := range s.IDs {
		m := new(models.TaskLogMysqlModel)
		m.TaskID = id
		m.DoStatus = s.Req.DoStatus
		m.Info = conv.StructToJsonString(s.Req.Info)
		v, _ := dao.LogDaoServer.Create(m)
		num = num + int(v)
	}
	return num
}

func (s *UpdateTaskStatus) GetList() {
	s.List, _ = new(dao.TaskDao).FindByIDs(s.IDs)
}

func (s *UpdateTaskStatus) Finish() {
	if len(s.List) <= 0 {
		return
	}
	if !(s.Req.DoStatus == enum.DoStatusSuccess || s.Req.DoStatus == enum.DoStatusFail) {
		return
	}
	for _, id := range s.IDs {
		t := dao.TaskDaoServer.GetTaskByList(id, s.List)
		//fmt.Printf("t: %+v \n", t)
		if t.IsNotify != 1 {
			continue
		}
		dao.FinishDaoServer.CreateByTaskModel(t, s.Req.DoStatus)
	}
}

func (s *UpdateTaskStatus) NewReady() {
	if s.Req.DoStatus != enum.DoStatusNew || len(s.List) <= 0 {
		return
	}
	for _, id := range s.IDs {
		t := dao.TaskDaoServer.GetTaskByList(id, s.List)
		dao.ReadyDaoServer.CreateByTaskModel(t)
	}
	dao.TaskDaoServer.UpdateDoStatus(s.IDs, enum.DoStatusNew)
}
